package javawdw.io.simple;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javawdw.io.BinaryReader;

public final class IOLoader {
	/**
	 * 将文件读取到byte数组中
	 * 
	 * @param file
	 *            要读取的文件
	 * @return 返回文件byte数组
	 */
	public static byte[] loadFileTobytes(InputStream inputStream) {
		BinaryReader reader = ReaderFactory.openBinaryReader(inputStream);
		byte[] buf = new byte[reader.available()];
		reader.read(buf);
		reader.close();
		return buf;
	}

	/**
	 * 获取文件File对象, 支持绝对路径和类路径参数
	 * 
	 * @param fileUrl
	 *            绝对路径或相对ClassPath路径
	 * @return 若文件存在,返回File对象,否则返回null
	 */
	public static File loadFile(String fileUrl) throws FileNotFoundException {
		File file = null;
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();
		try {
			file = new File(classLoader.getResource(fileUrl).getFile());
		} catch (Exception e1) {
			file = new File(fileUrl);
			if (!file.exists()) {
				throw new FileNotFoundException(fileUrl + " not found!");
			}
		}
		return file;
	}

	/**
	 * 根据给定路径获取文件的输入流对象
	 * 
	 * @param fileUrl
	 *            给定文件路径
	 * @return 返回得到的输入流
	 * @throws FileNotFoundException
	 *             文件不存在时抛出此异常
	 */
	public static InputStream loadInputStream(String fileUrl)
			throws FileNotFoundException {
		File file = loadFile(fileUrl);
		return new FileInputStream(file);
	}
}
